package cn.easyutil.veteran.web.handler;

import cn.easyutil.veteran.core.entity.SessionUser;
import cn.easyutil.veteran.core.utils.SpringUtils;
import cn.easyutil.veteran.web.advice.BeforeRequestAdvice;
import cn.easyutil.veteran.web.provider.DefaultBeforeRequestAdvice;
import cn.easyutil.veteran.web.session.SessionOperation;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 请求前置校验
 */
@Component
public class BeforeRequestHandle implements HandlerInterceptor {

    private BeforeRequestAdvice advice;
    private final BeforeRequestAdvice defaultAdvice = new DefaultBeforeRequestAdvice();

    /**
     * 访问接口之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        SessionOperation.clear();
        SessionOperation.request();
        getAdvice().beforeAuth(request);
        if(!SessionOperation.toAuth.get()){
            return true;
        }
        SessionUser user = SessionOperation.getUser();
        SessionOperation.refresh();
        getAdvice().afterAuth(request,user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            Method method = hm.getMethod();
            getAdvice().afterCompletion(request,method);
        }
        //移除掉保存的当前登陆用户的Token
        SessionOperation.clear();
    }

    private BeforeRequestAdvice getAdvice(){
        if(advice != null){
            return advice;
        }
        advice = SpringUtils.getBean(BeforeRequestAdvice.class);
        if(advice != null){
            return advice;
        }
        return defaultAdvice;
    }
}
